import 'dart:convert';
import 'dart:io';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart' hide Response;
import 'package:part_time_job_pro/common/index.dart';
import 'package:part_time_job_pro/common/utils/common.dart';

//登录认证
class AuthInterceptor extends InterceptorsWrapper {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
    LogUtil.e('----------AuthInterceptor onRequest------------');
    String? accessToken = CommonUtil.getLoginToken();
    ///在请求头设置token
    if (CommonUtil.isNotEmpty(accessToken)) {
      LogUtil.e('--------从缓存中获取到的token:$accessToken');
      options.headers['authorization'] = 'Bearer $accessToken';
    }

    ///处理请求类型
    LogUtil.e(options.uri, tag: "options.uri");
    String requestUrl = options.uri.toString();
    if (requestUrl.contains("/save")) {
      options.headers["Content-Type"] = Headers.jsonContentType;
      LogUtil.e("设置content-type为json模式成功!");
    }
    return handler.next(options);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    LogUtil.e('----------TokenInterceptor onResponse------------');
    LogUtil.e(response.statusCode, tag: "response.statusCode==>");
    EasyLoading.dismiss();
    if (response.statusCode == 200 || response.statusCode == 201) {
      //处理Token已经失效
      var data = response.data;
      if (data is Map) {
        if (data.containsKey(ResponesCode.codeTag)) {
          int code = data[ResponesCode.codeTag];
          if (code == ResponesCode.serverError) {
            String? message = data[ResponesCode.msgTag];
            EasyLoading.showToast(message!);
            return;
          }
        }
      } else {
        var result = jsonDecode(data);
        int resultCode = result[ResponesCode.codeTag];
        if (resultCode == ResponesCode.unauthorizedError) {
          EasyLoading.showToast("登录失效，请重新登录");
          loginOut();
        }
      }
    } else {
      //登录验证已过期 全局控制退出
      loginOut();
    }
    return handler.next(response);
  }

  //退出登录
  loginOut() {
    LogUtil.e('------当前token过期 退出登录！ ---------');
    UserApi().loginOut((data) {
      LogUtil.e('------退出登录成功 ---------');
      CommonUtil.clearLoginInfo();
      Get.offAllNamed(AppRoutes.userLogin);
    });
  }

  @override
  Future onError(DioException e, handler) async {
    logs("onError 收到错误信息 ：${e.message}");
    EasyLoading.dismiss();
    if (e.response == null) {
      if (e.type == DioExceptionType.connectionTimeout) {
        EasyLoading.showToast("请求超时，请检查网络");
      }
      return handler.next(e);
    }
    final int? code = e.response?.statusCode;
    if (code! <= 200) {
      return handler.next(e);
    } else if (code == 500) {
      final Map<String, dynamic> tempData = e.response?.data;
      logs("App请求数据出错：\n$tempData");
      final String? msg = tempData["msg"];
      final String? tempCode = tempData['code'];
      EasyLoading.showToast(msg!);
      return handler.reject(
        DioException(
          requestOptions: e.requestOptions,
          response: e.response,
          error: msg,
          message: jsonEncode({"msg": msg, "code": tempCode}),
          type: DioExceptionType.badResponse,
        ),
      );
    } else if (code == 401) {
      EasyLoading.showToast("登录失效，请重新登录");
      loginOut();
      return handler.reject(
        DioException(
          requestOptions: e.requestOptions,
          response: e.response,
          error: "登录失效，请重新登录",
          message: jsonEncode({"msg": "登录失效，请重新登录", "code": 401}),
          type: DioExceptionType.badResponse,
        ),
      );
    } else {
      if (e.response?.data == null) {
        EasyLoading.showToast("服务器异常");
      } else {
        if (e.response?.data is String) {
          EasyLoading.showToast("服务器异常");
        } else {
          final Map<String, dynamic> dataMap = e.response?.data;
          if (dataMap.isNotEmpty && dataMap.containsKey("msg")) {
            final String? msg = e.response?.data.msg;
            logs("服务器真的报错了，$msg");
            EasyLoading.showToast(msg ?? "服务器异常");
          } else {
            EasyLoading.showToast("服务器异常");
          }
        }
      }
    }
    return handler.next(e);
  }
}
